// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <pollux/common/testutil/test_value.h>

namespace kumo::pollux::common::testutil {
    std::mutex TestValue::mutex_;
    bool TestValue::enabled_ = false;
    melon::F14FastMap<std::string, TestValue::Callback> TestValue::injectionMap_;

#ifndef NDEBUG
    void TestValue::enable() {
        std::lock_guard<std::mutex> l(mutex_);
        enabled_ = true;
    }

    void TestValue::disable() {
        std::lock_guard<std::mutex> l(mutex_);
        enabled_ = false;
    }

    bool TestValue::enabled() {
        std::lock_guard<std::mutex> l(mutex_);
        return enabled_;
    }

    void TestValue::clear(const std::string &injectionPoint) {
        std::lock_guard<std::mutex> l(mutex_);
        injectionMap_.erase(injectionPoint);
    }

    void TestValue::adjust(const std::string &injectionPoint, void *testData) {
        Callback injectionCb; {
            std::lock_guard<std::mutex> l(mutex_);
            if (!enabled_ || injectionMap_.count(injectionPoint) == 0) {
                return;
            }
            injectionCb = injectionMap_[injectionPoint];
        }
        injectionCb(testData);
    }
#else
void TestValue::enable() {}
void TestValue::disable() {}
bool TestValue::enabled() {
  return false;
}
void TestValue::clear(const std::string& injectionPoint) {}
#endif
} // namespace kumo::pollux::common::testutil
